package com.sline.day02._04_getPrimaryKey;

import com.sline.util.JdbcUtil;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class autoGetPK {

    @Test
    public void statementGetKey() throws Exception {
        String sql = "insert into t_student(name, age) values('郭靖', 33)";

        Connection connection = JdbcUtil.getConnection();
        Statement statement = connection.createStatement();
        statement.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
        ResultSet rs = statement.getGeneratedKeys();
        if (rs.next()) {
            System.out.println("创建的数据的id是：" + rs.getLong(1));
        }

        JdbcUtil.close(connection, statement, rs);
    }

    @Test
    public void preparedStatementGetKey() throws Exception {
        String sql = "insert into t_student(name, age) values(?, ?)";

        Connection connection = JdbcUtil.getConnection();

        PreparedStatement preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        preparedStatement.setString(1, "黄蓉");
        preparedStatement.setInt(2, 23);

        preparedStatement.executeUpdate();

        ResultSet rs = preparedStatement.getGeneratedKeys();
        if (rs.next()) {
            System.out.println("创建数据的id是：" + rs.getLong(1));
        }
    }
}
